#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <unicode/ustream.h>
#include "MessageReprConverter.h"
#include "../data/Attachment.h"
#include "../data/BodyPart.h"

#define foreach BOOST_FOREACH
//#define DEBUG

namespace ba = boost::algorithm;
using namespace kc_sf;

// -------------------------------------------------------------- //

MessageReprConverter::~MessageReprConverter()
{
	if( m_output )
		delete m_output;
}

// -------------------------------------------------------------- //

Message MessageReprConverter::operator()( Entity &input, const RawMessage &rmsg )
{
	if( m_output )
		delete m_output;

	m_output = new Message( rmsg );

	// przepisujemy naglowki
	foreach( Header *header, input.getHeaders() )
	{
		m_output->addHeader( header );
	}
	m_output->mBcc = input.eBcc;
	m_output->mCc = input.eCc;
	m_output->mFrom = input.eFrom;
	m_output->mSubject = input.eSubject.trim();
	m_output->mTo = input.eTo;
	m_output->mSize = input.eSize;
	m_output->mContentType = input.eContentType;

#ifdef DEBUG
	std::cout << "From: " << m_output->mFrom.toString() << std::endl;
	std::cout << "To[0]: " << m_output->mTo[0].toString() << std::endl;
	std::cout << "Size: " << m_output->mSize << std::endl;
#endif // DEBUG

	convert( input );

	return *m_output;
}

// -------------------------------------------------------------- //

void MessageReprConverter::convert( Entity &entity )
{
	if( entity.isSinglepart() )
	{
		ContentType ct = entity.eContentType;
		// cialo <=> content-type == text
		if( ct.isBodyText() )
		{
			BodyPart *body = new BodyPart(
					entity.eData,
					entity.eEncoding,
					entity.eCharset );
			m_output->addBodyPart( *body );

#ifdef DEBUG
			std::cout << "BodyPart: charset: " << entity.eCharset << ", size: " << body->getSize() << std::endl;
#endif // DEBUG

			delete body;
		}
		else // zalacznik
		{
			Attachment *attch = new Attachment(
					entity.eData,
					entity.eEncoding,
					entity.eCharset,
					entity.eContentType );
			attch->aFilename = entity.eContentType.getParameter("name");
			m_output->addAttachment( attch );

#ifdef DEBUG
			std::cout << "Attachment: " << attch->getContentType().getType() << "/" << attch->getContentType().getSubtype()
					<< "; size: " << attch->getSize() << ", filename: " << attch->aFilename << std::endl;
			std::cout << "Message has " <<  m_output->mAttachments.size() << " attachments"  << std::endl;
#endif // DEBUG

			delete attch;
		}
	}
	else // multipart
	{
		foreach( Entity *child, entity.getChildren() )
		{
			convert( *child );
		}
	}
}
